import getLastEvent from "../uilts/getList";
import getSelector from "../uilts/getSelector";
import tracker from "../uilts/tracker";
export function injectJsError() {
  // 监理全局未捕获的错误
  window.addEventListener(
    "error",
    function (event) {
      //这是一个脚本加载错误 比如加载js

      if (event.target && (event.target.src || event.target.href)) {
        let lastEvent = getLastEvent(); //最后一个交互事件
        //错误时间对象
        let log = {
          kind: "stabillity", //监控指标的大类
          type: "error", //小类型 这个一个错误
          errorType: "resourceError", //js 或者css 加载错误
          url: "", //访问那个路径报错
          // message: event.message, //报错信息
          filename: event.target.src || event.target.href, //那个文件报错了
          postition: `${event.lineno}:${event.colno}`,
          stack: getLines(event.error.stack), //堆栈信息
          //返回选择器
          selector: lastEvent ? getSelector(lastEvent.path) : "", //代表最后一个操作的元素
        };
        tracker.send(log);
      } else {
        let lastEvent = getLastEvent(); //最后一个交互事件
        // //错误时间对象
        // console.log(event, lastEvent, "event");
        let log = {
          kind: "stabillity", //监控指标的大类
          type: "error", //小类型 这个一个错误
          errorType: "jsError", //js 执行错误
          url: "", //访问那个路径报错
          message: event.message, //报错信息
          filename: event.filename, //那个文件报错了
          postition: `${event.lineno}:${event.colno}`,
          stack: getLines(event.error.stack), //堆栈信息
          //返回选择器
          selector: lastEvent ? getSelector(lastEvent.path) : "", //代表最后一个操作的元素
        };
        tracker.send(log);
      }
    },
    true
  );
  //处理promise错误异常
  window.addEventListener("unhandledrejection", (event) => {
    console.log("unhandledrejection", event);

    let lastEvent = getLastEvent(); //最后一个交互事件
    let message;
    let reason = event.reason; //promise 失败的愿意
    let filename;
    let lineno;
    let colno;
    let stack = "";
    if (typeof reason === "string") {
      message = reason;
    } else if (typeof reason === "object") {
      //说明是一个错误对象
      //  at http://localhost:8080/:25:34\n
      if (reason.stack) {
        let matchResult = reason.stack.match(/at\s+(.+):(\d+):(\d+)/);
        filename = matchResult[1];
        lineno = matchResult[2];
        colno = matchResult[3];
      }
      message = reason.stack.message;
      stack = getLines(reason.stack);
    }
  });

  //格式化堆栈信息
  function getLines(stack) {
    // console.log(stack.split('\n'),'stack')
    return stack
      .split("\n")
      .slice(1)
      .map((item) => item.replace(/^\s+at\s+/g, ""))
      .join("^");
  }
}
